<template>
    <div>
         <!--面包屑导航栏区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片区域-->
        <el-card>
            <!--添加警告提示-->
            <el-row class="margin">
                <el-col><el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert></el-col>
            </el-row>
            <!--商品分类选择级联框-->
            <span>选择商品分类：</span>
            <el-cascader
                v-model="selectedOption"
                :options="categoriesList"
                :props="cascaderprops"
                clearable
                change-on-select
                @change="categoryChanged"></el-cascader>
            <!--商品参数标签页区域-->
            <el-tabs v-model="activeName" @tab-click="handleClick" class="margin">
                <el-tab-pane label="动态参数" name="many">
                    <el-button size="mini" type="primary" @click="showAddDialog" :disabled="isDisabled">添加参数</el-button>
                    <!--商品动态参数表格区域-->
                    <el-table :data="manyTableData" style="width: 100%" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(scope.row, index)">{{item}}</el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index" label="排序"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                 <!--商品静态属性表格区域-->
                <el-tab-pane label="静态属性" name="only">
                    <el-button size="mini" type="primary" @click="showAddDialog" :disabled="isDisabled">添加属性</el-button>
                    <el-table :data="onlyTableData" style="width: 100%" border stripe>
                        <el-table-column type="index" label="排序"></el-table-column>
                        <el-table-column prop="attr_name" label="属性名称"></el-table-column>
                        <el-table-column prop="attr_vals" label="属性信息"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--添加参数的对话框-->
        <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>
<script>
export default {
    data () {
        return {
            selectedOption: [],
            categoriesList: [],
            cascaderprops: {
                value: 'cat_id',
                label: 'cat_name',
                children: 'children',
                expandTrigger: 'hover'
            },
            activeName: 'many',
            addDialogVisible: false,
            manyTableData: [],
            onlyTableData: [],
            addFormRules: {
            attr_name: [
                { required: true, message: '请输入分类名称', trigger: 'blur' },
                { min: 1, max: 10, message: '长度在1到10个字符', trigger: 'blur' }
            ]
        },
            addForm: {
                attr_name: ''
                },
            editDialogVisible: false,
            editForm: {
                attr_name: ''
            }
        }
    },
    created () {
        this.getCategoryList()
    },
    methods: {
        // 获取商品分类列表
        async getCategoryList () {
            const { data: res } = await this.$http.get('categories')
            if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
            this.categoriesList = res.data
        },
        // 监听商品分类级联框
        categoryChanged () {
            this.getParamsData()
        },
        // 监听商品参数标签页
        handleClick (tab, event) {
            this.getParamsData()
        },
        // 打开添加参数对话框
        showAddDialog () {
            this.addDialogVisible = true
        },
        // 获取参数的列表数据
        async getParamsData() {
        // 证明选中的不是三级分类
        if (this.selectedOption.length !== 3) {
            this.selectedOption = []
            this.manyTableData = []
            this.onlyTableData = []
            return false
        }
        // 证明选中的是三级分类
        // 根据所选分类的Id，和当前所处的面板，获取对应的参数
        const { data: res } = await this.$http.get(`categories/${this.categoryId}/attributes`,
        {
          params: { sel: this.activeName }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败！')
        res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
            // 给数组中的每一项item都赋值一个单独的inputVisible和inputValue
            item.inputVisible = false
            item.inputValue = ''
        })
        if (this.activeName === 'many') {
            this.manyTableData = res.data
        } else {
            this.onlyTableData = res.data
        }
        console.log(res.data)
        },
        addDialogClosed () {
            this.$refs.addFormRef.resetFields()
        },
        editDialogClosed () {
            this.$refs.editFormRef.resetFields()
        },
        // 提交添加的参数
        async addParams () {
            const { data: res } = await this.$http.post(`categories/${this.categoryId}/attributes`, {
                attr_name: this.addForm.attr_name,
                attr_sel: this.activeName
            })
            if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
            this.$message.success('添加参数成功')
            if (this.activeName === 'many') {
             this.manyTableData.push(res.data)
            } else {
            this.onlyTableData.push(res.data)
        }
            this.addDialogVisible = false
        },
        async showEditDialog (id) {
            this.editDialogVisible = true
            const { data: res } = await this.$http.get(`categories/${this.categoryId}/attributes/${id}`, {
                attr_sel: this.activeName
            })
            if (res.meta.status !== 200) return this.$message.error('获取参数信息失败！')
            this.editForm = res.data
        },
        async editParams () {
            const { data: res } = await this.$http.put(`categories/${this.categoryId}/attributes/${this.editForm.attr_id}`, {
                attr_name: this.editForm.attr_name, attr_sel: this.activeName
            })
            if (res.meta.status !== 200) return this.$message.error('修改参数失败！')
            this.$message.success('修改参数成功！')
            this.getParamsData()
            this.editDialogVisible = false
        },
        async removeParams (id) {
            const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 用户取消了删除的操作
        if (confirmResult !== 'confirm') {
            return this.$message.info('已取消删除！')
        }
        // 删除的业务逻辑
        const { data: res } = await this.$http.delete(`categories/${this.categoryId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除参数失败！')
        this.$message.success('删除参数成功！')
        this.getParamsData()
        },
        showInput (row) {
            row.inputVisible = true
            // $nextTick方法的作用，就是当页面上元素被重新渲染后，才会执行回调函数中的代码
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus()
        })
        },
        async handleInputConfirm (row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = ''
                row.inputVisible = false
                return false
            }
            row.attr_vals.push(row.inputValue)
            row.inputValue = ''
            row.inputVisible = false
            // 发起请求，让后端保存此次数据
            const { data: res } = await this.$http.put(`categories/${this.categoryId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(',')
            })
            if (res.meta.status !== 200) return this.$message.error('添加参数失败！')
                this.$message.success('添加参数成功！')
        },
        async handleClose (row, index) {
            row.attr_vals.splice(index, 1)
            // 发起请求，让后端保存此次数据
            const { data: res } = await this.$http.put(`categories/${this.categoryId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: row.attr_vals.join(',')
            })
            if (res.meta.status !== 200) return this.$message.error('添加参数失败！')
                this.$message.success('添加参数成功！')
        }
    },
    computed: {
        isDisabled () {
            if (this.selectedOption.length !== 3) {
                return true
            }
            return false
        },
        categoryId () {
            if (this.selectedOption.length === 3) {
            return this.selectedOption[2]
            }
            return null
        },
        titleText () {
            if (this.activeName === 'many') {
            return '动态参数'
            }
            return '静态属性'
        }
    }
}
</script>
<style lang="less" scoped>
.margin{
    margin: 20px 0;
}
.padding{
    margin: 0 20px;
}
.el-tag{
    margin: 10px
}
.input-new-tag{
    width: 120px;
}

</style>
